﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 排班管理:班组设置服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class TeamsettingService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Teamsetting> _teamsettingRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public TeamsettingService(SqlSugarRepository<Teamsetting> teamsettingRep, ISqlSugarClient sqlSugarClient)
    {
        _teamsettingRep = teamsettingRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询排班管理:班组设置 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询排班管理:班组设置")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<TeamsettingOutput>> Page(PageTeamsettingInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _teamsettingRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.TeamSettingName.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TeamSettingName), u => u.TeamSettingName.Contains(input.TeamSettingName.Trim()))
            .LeftJoin<Teamtypes>((u, teamSettingType) => u.TeamSettingType == teamSettingType.Id)
            .LeftJoin<Personneltable>((u, teamSettingType, teamSettingMembers) => u.TeamSettingMembers == teamSettingMembers.Id)
            .Select((u, teamSettingType, teamSettingMembers) => new TeamsettingOutput
            {
                Id = u.Id,
                TeamSettingNumber = u.TeamSettingNumber,
                TeamSettingType = u.TeamSettingType,
                TeamSettingTypeFkDisplayName = $"{teamSettingType.TeamTypeName}",
                TeamSettingName = u.TeamSettingName,
                TeamSettingLeader = u.TeamSettingLeader,
                TeamSettingMembers = u.TeamSettingMembers,
                TeamSettingMembersFkDisplayName = $"{teamSettingMembers.PersonnelName}",
                TeamSettingNotes = u.TeamSettingNotes,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取排班管理:班组设置详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取排班管理:班组设置详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Teamsetting> Detail([FromQuery] QueryByIdTeamsettingInput input)
    {
        return await _teamsettingRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加排班管理:班组设置 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加排班管理:班组设置")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddTeamsettingInput input)
    {
        var entity = input.Adapt<Teamsetting>();
        return await _teamsettingRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新排班管理:班组设置 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新排班管理:班组设置")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateTeamsettingInput input)
    {
        var entity = input.Adapt<Teamsetting>();
        await _teamsettingRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除排班管理:班组设置 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除排班管理:班组设置")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteTeamsettingInput input)
    {
        var entity = await _teamsettingRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _teamsettingRep.FakeDeleteAsync(entity);   //假删除
        //await _teamsettingRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除排班管理:班组设置 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除排班管理:班组设置")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteTeamsettingInput> input)
    {
        var exp = Expressionable.Create<Teamsetting>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _teamsettingRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _teamsettingRep.FakeDeleteAsync(list);   //假删除
        //return await _teamsettingRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataTeamsettingInput input)
    {
        var teamSettingTypeData = await _teamsettingRep.Context.Queryable<Teamtypes>()
            .InnerJoinIF<Teamsetting>(input.FromPage, (u, r) => u.Id == r.TeamSettingType)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.TeamTypeName}"
            }).ToListAsync();
        var teamSettingMembersData = await _teamsettingRep.Context.Queryable<Personneltable>()
            .InnerJoinIF<Teamsetting>(input.FromPage, (u, r) => u.Id == r.TeamSettingMembers)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PersonnelName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "teamSettingType", teamSettingTypeData },
            { "teamSettingMembers", teamSettingMembersData },
        };
    }
    
    /// <summary>
    /// 导出排班管理:班组设置记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出排班管理:班组设置记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageTeamsettingInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportTeamsettingOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "排班管理:班组设置导出记录");
    }
    
    /// <summary>
    /// 下载排班管理:班组设置数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载排班管理:班组设置数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportTeamsettingOutput>(), "排班管理:班组设置导入模板", (_, info) =>
        {
            if (nameof(ExportTeamsettingOutput.TeamSettingTypeFkDisplayName) == info.Name) return _teamsettingRep.Context.Queryable<Teamtypes>().Select(u => $"{u.TeamTypeName}").Distinct().ToList();
            if (nameof(ExportTeamsettingOutput.TeamSettingMembersFkDisplayName) == info.Name) return _teamsettingRep.Context.Queryable<Personneltable>().Select(u => $"{u.PersonnelName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入排班管理:班组设置记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入排班管理:班组设置记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportTeamsettingInput, Teamsetting>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 班组类型
                    var teamSettingTypeLabelList = pageItems.Where(x => x.TeamSettingTypeFkDisplayName != null).Select(x => x.TeamSettingTypeFkDisplayName).Distinct().ToList();
                    if (teamSettingTypeLabelList.Any()) {
                        var teamSettingTypeLinkMap = _teamsettingRep.Context.Queryable<Teamtypes>().Where(u => teamSettingTypeLabelList.Contains($"{u.TeamTypeName}")).ToList().ToDictionary(u => $"{u.TeamTypeName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TeamSettingType = teamSettingTypeLinkMap.GetValueOrDefault(e.TeamSettingTypeFkDisplayName ?? "");
                            if (e.TeamSettingType == null) e.Error = "班组类型链接失败";
                        });
                    }
                    // 链接 班组人员
                    var teamSettingMembersLabelList = pageItems.Where(x => x.TeamSettingMembersFkDisplayName != null).Select(x => x.TeamSettingMembersFkDisplayName).Distinct().ToList();
                    if (teamSettingMembersLabelList.Any()) {
                        var teamSettingMembersLinkMap = _teamsettingRep.Context.Queryable<Personneltable>().Where(u => teamSettingMembersLabelList.Contains($"{u.PersonnelName}")).ToList().ToDictionary(u => $"{u.PersonnelName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TeamSettingMembers = teamSettingMembersLinkMap.GetValueOrDefault(e.TeamSettingMembersFkDisplayName ?? "");
                            if (e.TeamSettingMembers == null) e.Error = "班组人员链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Teamsetting>>();
                    
                    var storageable = _teamsettingRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.TeamSettingNumber?.Length > 32, "班组编号长度不能超过32个字符")
                        .SplitError(it => it.Item.TeamSettingName?.Length > 32, "班组名称长度不能超过32个字符")
                        .SplitError(it => it.Item.TeamSettingLeader?.Length > 32, "班组组长长度不能超过32个字符")
                        .SplitError(it => it.Item.TeamSettingNotes?.Length > 32, "备注长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
